import { computed, defineComponent } from "vue";
import { buildRequestEntity } from "./util";
import { useSize } from "element-plus";
import { useRequest } from "@/hooks";

function disableOption(options) {
  return options.map(v => {
    v.disabled = true
    v.children && (v.children = disableOption(v.children))
    return v
  })
}
export default defineComponent({
  name: "DynamicCascader",
  props: {
    width: {
      type: String,
      default: '180px'
    },
    requestUrl: String,
    params: Object,
    labelKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'id'
    },
    disableCache: {
      type: Boolean,
      default: true
    },
    size: String,
    isFormat: Boolean, // 返回最后一级数据
  },
  emits: ['update:modelValue'],
  setup: function (props, { expose, attrs, emit }) {
    const { disableCache, width, size, labelKey, valueKey, isFormat } = props
    const itemSize = useSize()
    const elSize = computed(() => size || itemSize.value)
    const { data, refreshData } = useRequest(buildRequestEntity(props), !disableCache)
    const opts = computed(() => {
      if (attrs.readonly)
        return disableOption(data.value)
      return data.value
    })
    expose({
      refreshOptions: refreshData
    })
    return () => (
      <el-cascader
        style={{ width }}
        size={elSize.value}
        options={opts.value}
        clearable={!attrs.readonly}
        onChange={(val) => {
          const v = isFormat ? (val ? val[val.length - 1] : undefined) : val
          emit('update:modelValue', v)
        }}
        props={
          {
            checkStrictly: true,
            label: labelKey,
            value: valueKey
          }
        }
        {...attrs}

      />
    )
  }
})
